import { getAppChanges } from '../applications/app';
import { toBootstrapPromise } from '../lifecycles/bootstrap';
import { toLoadPromise } from '../lifecycles/load';
import { toUnmountPromise } from '../lifecycles/unmount';
import { toMountPromise } from '../lifecycles/mount';
import './navigator-events' // 重载路由控制 从而实现切换路由时切换应用

import {
    started
} from '../start';


export function reroute() {
 
    // 1. 获取需要加载的应用
    // 2. 获取需要被挂载的应用
    // 3. 哪些应用需要被卸载
    const {
        appsToLoad,
        appsToMount,
        appsToUnmount
    } = getAppChanges();
    if (started) {
        // app装载
        console.log('调用start');
        return performAppChanges();
    }else{
        // 注册应用时 需要预加载
        console.log('调用register'); 
        return loadApps();
    }   
    // 预加载应用
    async function loadApps() {
        const apps = await Promise.all(appsToLoad.map(toLoadPromise)) // 获取到bootstrap mount unmount方法 放在状态机上
    }
    // 根据路径进行装载
    async function performAppChanges(params) {
        // 先卸载不需要的应用
        let unMountPromises = appsToUnmount.map(toUnmountPromise); 
        // 将需要加载的应用拿到  加载 - 启动 - 挂载
        appsToLoad.map(async (app)=>{
            app = toLoadPromise(app);
            app = await toBootstrapPromise(app);
            return await toMountPromise(app);
        })
        // 挂载
        appsToMount.map(async app => {
            app = toBootstrapPromise(app);
            return toMountPromise(app);
        })
    }
}